﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace CalcCalorie
{
    public partial class FormEditValue : Form
    {
        bool bOK = false;
        public string RetVal { get { return txbVal.Text; } set { txbVal.Text = value; } }

        public delegate string CheckRetValDelegate(string RetVal);
        CheckRetValDelegate CheckRetVal = null;

        bool selectText;

        public FormEditValue()
        {
            InitializeComponent();
        }

        public bool ShowDialog(string Caption, string startValue) { return ShowDialog(Caption, startValue, false, null); }

        public bool ShowDialog(string Caption, string startValue, bool selectText) { return ShowDialog(Caption, startValue, selectText, null); }

        public bool ShowDialog(string Caption, string startValue, bool selectText, CheckRetValDelegate CheckRetVal)
        {
            RetVal = startValue;
            bOK = false;
            lblCaption.Text = Caption;
            this.selectText = selectText;
            this.CheckRetVal = CheckRetVal;
            ShowDialog();
            return bOK;
        }

        private void txbVal_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) button1_Click(null, null);
            if (e.KeyCode == Keys.Escape) button2_Click(null, null);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (CheckRetVal != null)
            {
                string err = CheckRetVal(RetVal);
                if (err != "")
                {
                    MessageBox.Show(err);
                    return;
                }
            }
            bOK = true;
            Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void FormEditValue_Shown(object sender, EventArgs e)
        {
            txbVal.Focus();
            if (selectText) txbVal.SelectAll();
            else txbVal.Select(txbVal.Text.Length, 0);
        }

    }
}
